package com.yc.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.study.entity.MenuRole;
import com.yc.study.entity.Role;
import com.yc.study.mapper.MenuRoleMapper;
import com.yc.study.mapper.RoleMapper;
import com.yc.study.service.IRoleService;
import com.yc.study.vo.ReturnDistributionVo;
import com.yc.study.vo.RoleVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色 服务实现类
 *
 * @author 王妍
 * @since 2022-02-20
 */
@Service
@AllArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

  private final RoleMapper roleMapper;
  private final MenuRoleMapper menuRoleMapper;

  @Override
  public List<String> loadUserRoleByUserId(Long userId) {
    return roleMapper.loadUserRoleByUserId(userId);
  }

  @Override
  public Page<RoleVo> loadPage(Page<RoleVo> roleVoPage, RoleVo roleVo) {
    return roleMapper.loadPage(roleVoPage, roleVo);
  }

  @Override
  public ReturnDistributionVo<Role> getRoleDistribution(Long userId) {
    ReturnDistributionVo<Role> returnDistributionVo = new ReturnDistributionVo<>();
    returnDistributionVo.setOwnRoles(
        roleMapper.selectByUserId(userId).stream().map(Role::getId).collect(Collectors.toList()));
    returnDistributionVo.setAllRoles(list());
    return returnDistributionVo;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void configureRoleForMenu(Long menuId, List<Long> asList) {
    menuRoleMapper.delete(new LambdaQueryWrapper<MenuRole>().eq(MenuRole::getMenuId, menuId));
    asList.stream().map(roleId -> new MenuRole(menuId, roleId)).forEach(menuRoleMapper::insert);
  }

  @Override
  public ReturnDistributionVo<Role> getRoleDistributionByMenuId(Long menuId) {
    ReturnDistributionVo<Role> returnDistributionVo = new ReturnDistributionVo<>();
    returnDistributionVo.setOwnRoles(
        roleMapper.selectByMenuId(menuId).stream().map(Role::getId).collect(Collectors.toList()));
    returnDistributionVo.setAllRoles(list());
    return returnDistributionVo;
  }
}
